$(function () {
    init();
    var productId = $("#productId").val();
    optionChangeFirst();
    getData(productId);
    sliderChange();
    assignment();
});
var prefix = "/home/productBrowsing"
var cprefix = "/home/compare"
var dateHint;
//初始化预览日期
function initDate(ncFileDate) {
    var markStr = "{";
    for (var i = 0; i < ncFileDate.length; i++) {
        if (i == 0) {
            markStr += "'" + ncFileDate[i] + "':'" + ncFileDate[i].substring(8, 10) + "'";
        }
        else {
            markStr += ",'" + ncFileDate[i] + "':'" + ncFileDate[i].substring(8, 10) + "'";
        }
    }
    markStr += '}';
    var mark = eval("(" + markStr + ")");
    //时间可以选择
    $("#date").attr("disabled", false);
    if (dateHint) {
        dateHint.config.mark = mark;
        laydate.render({
            mark: mark
        })
    } else {
        //场 比测日期
        dateHint = laydate.render({
            elem: '#date'
            , showBottom: false
            , trigger: 'click'
            , min: -180
            , max: 0
            , mark: mark
            , done: function (value, date, endDate) {
                var productId = $("#productId").val();
                $.ajax({
                    type: "post",
                    async: true,
                    url: cprefix+"/getNcfile",
                    data: {
                        "productId": productId,
                        "date": value
                    },
                    dataType: "json",        //返回数据形式为json
                    success: function (res) {
                        var result = res.data;
                        var yulanNcfile = $("#yulanNcfile");
                        var yulanNcfileName = $("#yulanNcfileName");
                        yulanNcfile.empty();
                        yulanNcfileName.empty();
                        if (result.length > 0) {
                            for (var i = 0; i < result.length; i++) {
                                var option = "<option value = '" + result[i].id + "'>" + result[i].fileName + "</option>";
                                yulanNcfile.append(option);
                                var option2 = "<option value = '" + result[i].fileName + "'>" + result[i].fileName + "</option>";
                                yulanNcfileName.append(option2);
                            }
                        } else {
                            var option = "<option value = ''>无</option>";
                            yulanNcfile.append(option);
                            var option2 = "<option value = ''>无</option>";
                            yulanNcfileName.append(option2);
                        }
                    }
                });
            }
        });
    }
}

function findNcFile() {
    $.ajax({
        type: "post",
        async: true,
        url: cprefix+"/getNcfile",
        data: {
            "productId": $("#productId").val(),
            "date": $("#date").val()
        },
        dataType: "json",        //返回数据形式为json
        success: function (res) {
            var result = res.data;
            var yulanNcfile = $("#yulanNcfile");
            var yulanNcfileName = $("#yulanNcfileName");
            yulanNcfile.empty();
            yulanNcfileName.empty();
            if (result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                    var option = "<option value = '" + result[i].id + "'>" + result[i].fileName + "</option>";
                    yulanNcfile.append(option);
                    var option2 = "<option value = '" + result[i].fileName + "'>" + result[i].fileName + "</option>";
                    yulanNcfileName.append(option2);
                }
            } else {
                var option = "<option value = ''>无</option>";
                yulanNcfile.append(option);
                var option2 = "<option value = ''>无</option>";
                yulanNcfileName.append(option2);
            }
        }
    });
}

function init() {
    //sliderInit
    $('#longSlider').jRange({
        from: -90,
        to: 90,
        step: 1,
        format: '%s',
        width: 300,
        showLabels: true,
        isRange: true
    });

    $('#latiSlider').jRange({
        from: -90,
        to: 90,
        step: 1,
        format: '%s',
        width: 300,
        showLabels: true,
        isRange: true
    });

    //checkBoxInit
    $(".checkbox").toggle(
        function () {
            $(".speedbox").slideToggle(400);
            $(this).addClass("checkboxactive")
        }, function () {
            $(".speedbox").slideToggle(400);
            $(this).removeClass("checkboxactive")
        });
    $('.collapse.in').prev('.panel-heading').addClass('active');
    $('#accordion, #bs-collapse').on('show.bs.collapse', function (a) {
        $(a.target).prev('.panel-heading').addClass('active');
    }).on('hide.bs.collapse', function (a) {
        $(a.target).prev('.panel-heading').removeClass('active');
    });

    $('.radio').each(function (i) {
        $(this).click(function () {
            $("#elementType").val(i);
            $('.radio').css("background-image", "");
            $(this).css("background-image", "url(/static/img/radio_img.png)");
            if (i == 1) {
                $("#yulanEmelentLabel").html("U");
                $("#yulanEmelentLabel2").html("V");
            } else if (i == 2) {
                $("#yulanEmelentLabel").html("速度（波高）");
                $("#yulanEmelentLabel2").html("方向（波向）");
            }
            if ($("#elementType").val() == 1) {
                $("#out2Div").css("display", "");
                optionChangeSecond();
            } else if ($("#elementType").val() == 2) {
                $("#out2Div").css("display", "");
                optionChangeThird();
            } else if ($("#elementType").val() == 0) {
                $("#yulanEmelentLabel").html("要素");
                $("#out2Div").css("display", "none");
                optionChangeFirst();
            } else {
                optionChangeFirst();
            }
        })
    });
};

var elementsdb = [];
function getData(productId) {
    //时间禁止选择
    $("#date").attr("disabled", true);
    $.ajax({
        type: "post",
        async: true,
        url: prefix+"/getPreviewData",
        data: {
            "productId": productId
        },
        dataType: "json",        //返回数据形式为json
        success: function (res) {
            var result = res.data;
            var data = result[0].param;
            initDate(result[0].ncFileDate);
            for (var i = 0; i < data.length; i++) {
                var value = data[i];
                if (value.isOutParameter == 0 && value.elementZh == "时间") {
                    $("#timeDiv").css("display", "");
                    $("#timeLabel").css("display", "");
                    $("#timeSelect").css("display", "");
                    var realValues = value.realValue.split(",");
                    for (var j = 0; j < realValues.length; j++) {
                        var realValue = realValues[j];
                        $("#timeSelect").append("<option value='" + realValue + "'>" + realValue + "</option>");
                    }
                    elementsdb.push(value.elementZh + ";" + value.elementEn);
                }
                if (value.isOutParameter == 0 && value.elementZh == "经度") {
                    var range = value.minValue + "," + value.maxValue;
                    $('#longSlider').jRange('updateRange', range, range);
                    $('#longDiv').css("display", "");
                    $('#longRange').text("取值范围：" + value.minValue + "~" + value.maxValue);
                    $("#longMinVal").val(value.minValue);
                    $("#longMaxVal").val(value.maxValue);
                    elementsdb.push(value.elementZh + ";" + value.elementEn);
                }
                if (value.isOutParameter == 0 && value.elementZh == "纬度") {
                    var range = value.minValue + "," + value.maxValue;
                    $('#latiSlider').jRange('updateRange', range, range);
                    $('#latiDiv').css("display", "");
                    $('#latiRange').text("取值范围：" + value.minValue + "~" + value.maxValue);
                    $("#latMinVal").val(value.minValue);
                    $("#latMaxVal").val(value.maxValue);
                    elementsdb.push(value.elementZh + ";" + value.elementEn);
                }
                if (value.isOutParameter == 0 && value.elementZh == "高度" || value.elementZh == "深度") {
                    $("#depthDiv").css("display", "");
                    var realValues = value.realValue.split(",");
                    for (var j = 0; j < realValues.length; j++) {
                        var realValue = realValues[j];
                        $("#depth").append("<option value='" + realValue + "'>" + realValue + "</option>");
                    }
                    elementsdb.push(value.elementZh + ";" + value.elementEn);
                }
                if (value.isOutParameter == 1) {
                    $("#out").append("<option value='" + value.elementEn + "'>" + value.elementEn + "</option>");
                    $("#out2").append("<option value='" + value.elementEn + "'>" + value.elementEn + "</option>");
                }
            }
        }
    });
}

function doPreview() {
    var ncFileId = $("#yulanNcfile").val();
    if (!ncFileId) {
        alert("预览文件不能为空");
        return;
    }
//    $("#preview").val("系统处理中...");
//    $("#preview").attr("disabled", true);
    var elementDtos = new Array();
    for (var i in elementsdb) {
        var elements = elementsdb[i].split(";");
        var element = elements[0];
        var elementEn = elements[1];
        if (element == "高度" || element == "深度") {
            var depth = $("#depth").val();
            elementDto = {
                element: elementEn,
                minValue: depth,
                maxValue: depth,
                flag: "-1"
            };
        }
        if (element == "时间") {
            var time = $("#timeSelect").val();
            elementDto = {
                element: elementEn,
                minValue: time,
                maxValue: time,
                flag: "-1"
            };
        }
        if (element == "纬度") {
            elementDto = {
                element: elementEn,
                minValue: $("#latMinVal").val(),
                maxValue: $("#latMaxVal").val(),
                flag: "1"
            };
        }
        if (element == "经度") {
            elementDto = {
                element: elementEn,
                minValue: $("#longMinVal").val(),
                maxValue: $("#longMaxVal").val(),
                flag: "0"
            };
        }
        elementDtos.push(elementDto);
    }
    var yaosu = $("#out").val();
    var yaosu2 = "";
    if ($("#out2Div").css("display") != "none") {
        yaosu2 = $("#out2").val();
    }
    var type = $("#type").val();
    var productId = $("#productId").val();
    var date = $("#date").val();
    var yulanNcfile = $("#yulanNcfile").val();
    var yulanNcfileName = $("#yulanNcfileName").val();
    var timeLabel = $("#timeLabel").val();
    var inContent = "      要素：" + yaosu + "      预报时间：" + date + "      单位：m";
    var data = {
        "productId": productId,
        "ncFileId": ncFileId,
        "yulanNcfile": yulanNcfile,
        "timeLabel": timeLabel,
        "yulanNcfileName":yulanNcfileName,
        "date": date,
        "yaosu": yaosu,
        "yaosu2": yaosu2,
        "type": type,
        "workDto": elementDtos
    };

    layer.open({
        type: 2,
        title: '预览结果',
        shadeClose: true,
        shade: false,
        maxmin: true, //开启最大化最小化按钮
        resize: true,
        area: ['900px', '700px'],
        content: prefix+'result',
        success: function (layero, index) {
            var body = layer.getChildFrame('body', index);
            var timerDiv = body.find('#timer');
            var imageDiv = body.find("#imageDiv");
            var resultImg = body.find('#resultImg');
            var ace = body.find('#ace');
            var tittle = body.find('#tittle');
            var createWordDiv = body.find('#createWordDiv');
            var iframeWin = window[layero.find('iframe')[0]['name']];
            $.ajax({
                type: "post",
                async: true,
                url: prefix+"preview",
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify(data),
                dataType: "json",        //返回数据形式为json
                success: function (res) {
                    var result = res.data
                    timerDiv.hide();
                    imageDiv.show();
                    ace.html(inContent);
                    tittle.html(yulanNcfileName);
                    if (result.code == web_status.SUCCESS) {
                        ace.html(inContent);
                        tittle.html(yulanNcfileName);
                        resultImg.attr("src", result.obj);
                        resultImg.attr("width","800px");
                        resultImg.attr("height","600px");
                        iframeWin.setData(JSON.stringify(data), result.obj);
                        createWordDiv.css("display", "block");
                    }
                    else {
                        iframeWin.open(res.msg);
                        resultImg.attr("src", "webpage/web/images/notfound.png");
                        resultImg.attr("width","600px");
                        resultImg.attr("height","400px");

                    }
//                    $("#preview").val("确认");
//                    $("#preview").attr("disabled", false);
                },
                error: function (result) {
                    timerDiv.hide();
                    imageDiv.show();
                    iframeWin.open("预览失败。");
                    resultImg.attr("src", "/static/img/notfound.png");
//                    $("#preview").val("确认");
//                    $("#preview").attr("disabled", false);
                }
            });
        }
    });
}

function optionChangeThird() {
    $("#type").empty();
    var value = new Array("12", "13", "14");
    var text = new Array("风场", "流场", "浪场");
    for (var int = 0; int < 3; int++) {
        $("#type").append("<option value='" + value[int] + "'>" + text[int] + "</option>")
    }
}

function optionChangeSecond() {
    $("#type").empty();
    var value = new Array("9", "10", "11");
    var text = new Array("风场", "浪场", "流场");
    for (var int = 0; int < 3; int++) {
        $("#type").append("<option value='" + value[int] + "'>" + text[int] + "</option>")
    }
}

function optionChangeFirst() {
    $("#type").empty();
    var value = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8");
    var text = new Array("海温", "盐度", "气温", "相对湿度", "气压", "有效波高", "风速", "流速", "其它");
    for (var int = 0; int < 9; int++) {
        $("#type").append("<option value='" + value[int] + "'>" + text[int] + "</option>")
    }

}

function optionChange15() {
    $("#type").empty();
    var value = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14");
    var text = new Array("海温", "盐度", "气温", "相对湿度", "气压", "有效波高", "风速", "流速", "其它", "风场", "浪场", "流场", "风场", "流场", "浪场");
    for (var int = 0; int < 15; int++) {
        $("#type").append("<option value='" + value[int] + "'>" + text[int] + "</option>")
    }

}

var reg = "^[\\+\\-]?[\\d]+(\\.[\\d]+)?$";
var re = new RegExp(reg);
$("#longMinVal").change(function () {
    var value = $('#longSlider').jRange('getRange').split(",");
    if (!re.test($("#longMinVal").val())) {
        $("#longMinVal").val(value[0]);
        alert("请输入正确格式");
        return;
    }
    if (parseFloat($("#longMinVal").val()) < parseFloat(value[0]) || parseFloat($("#longMinVal").val()) > parseFloat($("#longMaxVal").val())) {
        $("#longMinVal").val(value[0]);
        alert("请输入正确值");
        return;
    }
    var value = $('#longSlider').jRange('getRange').split(",");
    var range = $("#longMinVal").val() + "," + $("#longMaxVal").val();
    $('#longSlider').jRange('setValue', range);
});

$("#longMaxVal").change(function () {
    var value = $('#longSlider').jRange('getRange').split(",");
    if (!re.test($("#longMaxVal").val())) {
        $("#longMaxVal").val(value[1]);
        alert("请输入正确格式");
        return;
    }
    if (parseFloat($("#longMaxVal").val()) > parseFloat(value[1]) || parseFloat($("#longMinVal").val()) > parseFloat($("#longMaxVal").val())) {
        $("#longMaxVal").val(value[1]);
        alert("请输入正确值");
        return;
    }
    var value = $('#longSlider').jRange('getRange').split(",");
    var range = $("#longMinVal").val() + "," + $("#longMaxVal").val();
    $('#longSlider').jRange('setValue', range);
});

$("#latMinVal").change(function () {
    var value = $('#latiSlider').jRange('getRange').split(",");
    if (!re.test($("#latMinVal").val())) {
        $("#latMinVal").val(value[0]);
        alert("请输入正确格式");
        return;
    }
    if (parseFloat($("#latMinVal").val()) < parseFloat(value[0]) || parseFloat($("#latMinVal").val()) > parseFloat($("#latMaxVal").val())) {
        $("#latMinVal").val(value[0]);
        alert("请输入正确值");
        return;
    }
    var value = $('#latiSlider').jRange('getRange').split(",");
    var range = $("#latMinVal").val() + "," + $("#latMaxVal").val();
    $('#latiSlider').jRange('setValue', range);
});

$("#latMaxVal").change(function () {
    var value = $('#latiSlider').jRange('getRange').split(",");
    if (!re.test($("#latMaxVal").val())) {
        $("#latMaxVal").val(value[1]);
        alert("请输入正确格式");
        return;
    }
    if (parseFloat($("#latMaxVal").val()) > parseFloat(value[1]) || parseFloat($("#latMinVal").val()) > parseFloat($("#latMaxVal").val())) {
        $("#latMaxVal").val(value[1]);
        alert("请输入正确值");
        return;
    }
    var value = $('#latiSlider').jRange('getRange').split(",");
    var range = $("#latMinVal").val() + "," + $("#latMaxVal").val();
    $('#latiSlider').jRange('setValue', range);
});
function sliderChange() {
    $('#longSlider').change(function () {
        var value = $('#longSlider').jRange('getValue').split(",");
        $("#longMinVal").val(value[0]);
        $("#longMaxVal").val(value[1]);
    });
    $('#latiSlider').change(function () {
        var value = $('#latiSlider').jRange('getValue').split(",");
        $("#latMinVal").val(value[0]);
        $("#latMaxVal").val(value[1]);
    });

}
function assignment() {
    var ncFileId = $("#ncFileId").val();
    var ncFileName = $("#ncFileName").val();
    var ncFileUpdateDate = $("#ncFileUpdateDate").val();
    $('#date').val(ncFileUpdateDate);
    var yulanNcfile = $("#yulanNcfile");
    var yulanNcfileName = $("#yulanNcfileName");
    yulanNcfile.empty();
    yulanNcfileName.empty();
    var option = "<option value = '" + ncFileId + "'>" + ncFileName + "</option>";
    yulanNcfile.append(option);
    var option2 = "<option value = '" + ncFileName + "'>" + ncFileName + "</option>";
    yulanNcfileName.append(option2);

}
